package com.yungu.swift.api.route.v2.common;

import com.alibaba.dubbo.config.annotation.Reference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.collect.Lists;
import com.yungu.swift.api.config.ApplicationConfig;
import com.yungu.swift.api.config.NacosListener;
import com.yungu.swift.api.utils.RandomUtil;
import com.yungu.swift.assets.common.model.param.LoginInfoParam;
import com.yungu.swift.assets.driver.model.dto.DriverLogDto;
import com.yungu.swift.assets.driver.service.DriverLogService;
import com.yungu.swift.assets.passenger.model.dto.PassengerLogDto;
import com.yungu.swift.assets.passenger.service.PassengerLogService;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.base.model.config.ServerConfig;
import com.yungu.swift.common.model.dto.CommonTagDto;
import com.yungu.swift.common.service.CommonArticleService;
import com.yungu.swift.common.service.CommonConfigService;
import com.yungu.swift.common.service.CommonTagService;
import com.yungu.swift.constants.CommonConstant;
import com.yungu.swift.order.model.vo.CrosstownFareInfoVo;
import com.yungu.swift.order.service.OrderFareService;
import com.yungu.swift.order.service.OrderService;
import com.yungu.swift.utils.JsonUtils;
import com.yungu.swift.utils.MapUtils;
import com.yungu.swift.utils.ParamUtil;
import com.yungu.swift.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

import static com.yungu.swift.api.config.ApplicationConfig.*;
import static com.yungu.swift.api.config.NacosListener.ALIYUN_CONFIG;


/**
 * @author Zerrion
 * @description
 * @date 2018/10/17. <br>
 */
@RestController(value = "commonVariableApiV2")
@RequestMapping("/api/v2/common")
@Api(value = "系统通用变量接口V2", tags = "系统通用变量接口V2版")
public class CommonVariableApi {

    @Reference
    private CommonConfigService commonConfigService;
    @Reference
    private CommonTagService commonTagService;
    @Reference
    private OrderService orderService;
    @Reference
    private OrderFareService orderFareService;
    @Reference
    private DriverLogService driverLogService;
    @Reference
    private PassengerLogService passengerLogService;
    @Reference
    private CommonArticleService commonArticleService;


    @RequestMapping(value = {"/getConfig/{identify}"}, method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "获取app配置", response = ResponseData.class)
    public ResponseData<Map<String, Object>> getCommoncfg(
            @RequestHeader(value = "appid", required = false) String appid,
            @ApiParam(name = "identify", value = "身份 1乘客 2司机", required = true) @PathVariable("identify")
                    Integer identify) throws JsonProcessingException {
        // 获得阿里云相关配置
        Map<String, String> aliyunConfig = new HashMap<>(8);
        aliyunConfig.put("accessKeyId", RandomUtil.randomEncrypt(ALIYUN_CONFIG.getAccessKeyId()));
        aliyunConfig.put("accessKeySecret", RandomUtil.randomEncrypt(ALIYUN_CONFIG.getAccessKeySecret()));
        aliyunConfig.put("endpoint", RandomUtil.randomEncrypt(ALIYUN_CONFIG.getExtEndpoint()));
        aliyunConfig.put("tripRecordBucketName", RandomUtil.randomEncrypt(ALIYUN_CONFIG.getTripRecordBucketName()));

        Map<String, Object> result = new HashMap<>(16);
        result.put("aliyunConfig", JsonUtils.writeJsonStr(aliyunConfig));
        result.put("commonConfig", JsonUtils.writeJsonStr(COMMON_CONFIG));
        switch (identify) {
            case 1:
                result.put("version", pasVersion.longValue());
                result.put("passengerConfig", JsonUtils.writeJsonStr(PASSENGER_CONFIG));
                result.put("h5UrlConfig", buildH5Url(appid, identify));
                result.put("riskControlConfig", buildRiskControl(appid));
                break;
            case 2:
                result.put("version", driVersion.longValue());
                result.put("driverConfig", JsonUtils.writeJsonStr(DRIVER_CONFIG));
                result.put("h5UrlConfig", buildH5Url(appid, identify));
                break;
            default:
                break;
        }
        return ResponseData.buildSuccessResponse("获取成功", result);
    }

    /**
     * 获取乘客端下单风控设置
     *
     * @param appid
     * @return
     */
    private Map<String, Object> buildRiskControl(String appid) {
        ServerConfig.SystemBean systemBean = ApplicationConfig.SERVER_CONFIG.getSystem();
        Map<String, Object> map = MapUtils.build(8);
        //乘客叫单允许最小距离
        map.put("minDistance", ParamUtil.defaultIfNull(systemBean.getMinDistance(), 0));
        //乘客叫单允许最大距离
        map.put("maxDistance", ParamUtil.defaultIfNull(systemBean.getMaxDistance(), 9999));
        //是否限制城市
        map.put("theSameCity", systemBean.getCheckSameCity());
        //报警电话
        map.put("alarmTelphone", systemBean.getAlarmTel());
        return map;
    }

    /**
     * 获取移动端h5相关链接
     *
     * @param appid
     * @param side
     * @return
     */
    private List<Map<String, String>> buildH5Url(String appid, int side) {
        List<NacosListener.UrlConfig> h5UrlConfig = NacosListener.H5_URL_CONFIG;
        List<NacosListener.UrlConfig> configs = h5UrlConfig.stream().filter(urlConfig -> {
            Integer configSide = urlConfig.getSide();
            return configSide == 0 || configSide == side;
        }).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(configs)) {
            List<Map<String, String>> resultList = new ArrayList<>();
            for (NacosListener.UrlConfig urlConfig : configs) {
                Map<String, String> recordMap = new HashMap<>(3);
                recordMap.put("key", urlConfig.getKey());
                String value = urlConfig.getValue();
                if ("about".equals(urlConfig.getKey())) {
                    value = value + "?appid=" + appid + "&identify=" + side;
                } else {
                    value = value + "?appid=" + appid;
                }
                recordMap.put("value", value);
                resultList.add(recordMap);
            }
            return resultList;
        }
        return Lists.newArrayList();
    }

    @RequestMapping(value = {"/getDriRegCfg"}, method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "获取司机端H5可注册业务配置", response = ResponseData.class)
    public ResponseData<List<String>> getDriRegCfg(@ApiParam(name = "appid", value = "租户标识", required = true) @RequestParam String appid) {
        return ResponseData.buildSuccessResponse(DRIVER_CONFIG.getLogin().getDriverRegisterType());
    }

    @RequestMapping(value = {"/tag/list"}, method = {RequestMethod.POST})
    @ApiOperation(value = "通用标签获取接口", response = ResponseData.class)
    public ResponseData<List<Map<String, Object>>> tagList(@RequestHeader String appid, @RequestBody Map<String, Object> paraMap) {
        ResponseData<List<CommonTagDto>> responseData = commonTagService.list(paraMap);
        if (responseData.isSuccess() && CollectionUtils.isNotEmpty(responseData.getData())) {
            List<Map<String, Object>> result = new ArrayList<>();
            for (CommonTagDto commonTagDto : responseData.getData()) {
                Map<String, Object> map = new HashMap<>();
                map.put("tagCode", commonTagDto.getTagCode());
                map.put("tagName", commonTagDto.getTagName());
                result.add(map);
            }
            return ResponseData.buildSuccessResponse("获取标签成功", result);
        }
        return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "未找到标签");
    }

    @RequestMapping(value = {"/token/crosstown/order/fareItems"})
    @ApiOperation(value = "跨城订单费用项", response = ResponseData.class)
    public ResponseData<CrosstownFareInfoVo> fareItems(@RequestBody Map<String, Object> map) {
        String orderUuid;
        Integer identity;
        try {
            orderUuid = map.get("orderUuid").toString();
            identity = Integer.parseInt(map.get("identity").toString());
        } catch (Exception e) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "参数异常");
        }
        return orderFareService.crosstownFareItems(orderUuid, identity);
    }

    @RequestMapping(value = {"/token/addLoginLog"})
    @ApiOperation(value = "乘客司机登录日志", response = ResponseData.class)
    public ResponseData<Boolean> addLoginLog(@RequestBody LoginInfoParam loginInfoParam) {
        try {
            //乘客
            if (CommonConstant.PASSENGER == loginInfoParam.getIdentity()) {
                PassengerLogDto passengerLogDto = new PassengerLogDto();
                BeanUtils.copyProperties(loginInfoParam, passengerLogDto);
                passengerLogDto.setCreateOn(new Date());
                passengerLogDto.setCreateBy(loginInfoParam.getPassengerUuid());
                return passengerLogService.add(passengerLogDto);
            }
            //司机
            if (CommonConstant.DRIVER == loginInfoParam.getIdentity()) {
                DriverLogDto driverLogDto = new DriverLogDto();
                BeanUtils.copyProperties(loginInfoParam, driverLogDto);
                driverLogDto.setCreateOn(new Date());
                driverLogDto.setCreateBy(loginInfoParam.getDriverUuid());
                return driverLogService.add(driverLogDto);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "登录类型异常");
    }


    @RequestMapping(value = {"/getPrivacyPolicy"})
    @ApiOperation(value = "获取隐私策略文章", response = ResponseData.class)
    public ResponseData<Map<String, Object>> getAgreement(@RequestBody Map<String, Integer> paraMap) {
        Integer identity = paraMap.get("identity");
        if (ParamUtil.isIllegal(identity)) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "参数异常");
        }
        return commonArticleService.getPrivacyPolicy(identity);
    }

}
